<template>
  <div id="home">
    <div class="h-justify">
      <div class="profile-info-cell h-left v-center">
        <span>
  　　　   <img class="circle" :src="imgUrl" width="100px" height="100px">
        </span>
        <span class="leading-8">
          <div>
            Wallet Addr: {{ walletAddress }}
          </div>
          <div>
            Balance: {{ hsdBalance }}
          </div>
          <div>
            <span style="padding-right: 8px;">
              <button type="button"
                v-clipboard:copy="walletAddress"
                v-clipboard:success="onCopy"
                v-clipboard:error="onError">Copy address</button>
            </span>
            <!-- <span style="padding-left: 8px;" class="link"><a>Setting</a></span> -->
          </div>
        </span>
      </div>
      <div class="v-center" style="margin-right: 20px;">
        <span>
          <el-button @click="giveMeMoney">Buy HSD</el-button>
          <!-- 1000000000000000 * 100 -->
        </span>
      </div>
    </div>

    <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="All" name="1"></el-tab-pane>
        <el-tab-pane label="For sale" name="2"></el-tab-pane>
    </el-tabs>

    <!-- 空列表 -->
    <div class="h-center font-l" v-if="!hasHorses"> You don't have any Horses </div>

    <!-- 马列表 -->
    <el-scrollbar class="scroll-view" v-if="hasHorses">
      <div class="scroll-content">
        <el-row>
          <el-col :span="8" v-for="(o, idx) in validHorses" :key="idx" class="card-col">
            <el-card :body-style="{ padding: '0px' }" class="card-cell h-center" @click.native="onHorseClicked(o.id)">
              <!-- <img src="~examples/assets/images/hamburger.png" class="image"> -->
              <div style="margin-top: 10px;margin-bottom: 10px;">
                <div v-if="o.isSale">For sale = {{o.eth}} ETH</div>
              </div>

              <ve-radar
                width="280px"
                height="220px"
                :data="o.chartData"
                :settings="chartSettings"
                :tooltip-visible="false"
                :legend-visible="true"
                :colors="colors"
                :extend="extend"
                class="skill-charts"></ve-radar>

              <el-rate
                v-model="o.rateValue"
                disabled
                class="rate">
              </el-rate>

              <div class="card-bottom h-justify">
                <img class="circle" :src="o.imgUrl" width="100px" height="100px">
                <span class="v-bottom" style="color: #00ff00;">
                    <div>{{ o.name }}</div>
                  </span>
                <span class="trailing-4 v-bottom">
                  <div >Gen{{o.generationNum}}</div>
                </span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
  export default {
    name: 'home',
    data: function () {
      this.extend = {
        series: {
          label: {
            normal: {
              show: true
            }
          }
        }
      }

      this.chartSettings = {
        dimension: [],
        // 速度 加速度 力量 耐力 敏捷性 平衡性 弹跳 反应速度
        metrics: ['Speed', 'Acceleration', 'Strength', 'Endurance', 'Agile', 'Balancing', 'Bouncing'],
        dataType: 'normal'
      }

      this.colors = [
        '#00000000',
        '#2f4554'
      ]

      return {
        user: this.$store.state.user,
        currentDate: new Date(),
        activeName: '1',
        chartData: {
          rows: []
        },
        imgUrl: '',
        value5: 3.7,
        hasHorses: true,
        hsdBalance: 0,
        walletAddress: '',

        allHorsesIds: [],
        validHorses: []
      }
    },
    mounted () {
      console.log('Home form mounted')

      this.imgUrl = require('../../assets/img/user/head.jpg')
    },
    created () {
      console.log('Home form created')
      setTimeout(() => {
        // 查询用户信息
        if (this.$root.hasInit()) {
          this.getUserInfo()
        } else {
          setTimeout(() => {
            if (this.$root.hasInit()) {
              this.getUserInfo()
            } else {
              setTimeout(() => {
                this.getUserInfo()
              }, 20000)
            }
          }, 10000)
        }
      }, 5000)
    },
    methods: {
      getUserInfo () {
        console.log('get user info...')
        console.log('hasInit: ' + this.$root.hasInit())
        // 查询用户信息
        this.$root.callMatch({
          params: null,
          methodName: API.GET_ACCOUNTS,
          methodType: 'GET',
          success: (data) => {
            console.log('walletAddress = ' + data)
            this.walletAddress = data

            // 查询用户余额
            this.$root.callMatch({
              isProtected: true,
              methodName: API.GET_HSD_BALANCE,
              methodType: 'GET',
              success: data => {
                console.log(JSON.stringify(data))
                this.hsdBalance = data
              },
              failure: null
            })

            // 获取用户的马
            this.getHorses()
          },
          failure: null
        })
      },
      handleTabClick () {
        this.getHorses()
      },
      onCopy: function (e) {
        // alert('You just copied: ' + e.text)
      },
      onError: function (e) {
        alert('Failed to copy texts')
      },
//       传参
//        this.$route.push({path:'/xxx',query:{id:1}});//类似get传参，通过URL传递参数
//        this.$route.push({path:'/xxx',params:{id:1}});//类似post传参
//       接收参数
//        this.$route.query.id
//        this.$route.params.id
      onHorseClicked (value) {
        console.log('onHorseClicked')

        this.$router.push({
          path: '/horse',
          query: {
            id: value
          }
        })
      },
      giveMeMoney () {
        this.$root.callMatch({
          isProtected: false,
          methodName: API.BUY_HSD,
          params: this.walletAddress,
          amount: 1000000000000000 * 10,
          methodType: 'POST',
          event: 'BuyHsd',
          success: data => {
            console.log('BUY_HSD = ' + JSON.stringify(data))
            // this.buyHsdResult = data

            // 刷新HSD
            this.$root.callMatch({
              isProtected: true,
              methodName: API.GET_HSD_BALANCE,
              methodType: 'GET',
              success: data => {
                console.log(JSON.stringify(data))
                this.hsdBalance = data
              },
              failure: null
            })
          },
          failure: null
        })
      },
      getHorses () {
        this.$root.callMatch({
          isProtected: true,
          methodName: API.TOKENS_OF_OWNER,
          methodType: 'GET',
          success: data => {
            // console.log('getHorses = ' + JSON.stringify(data))
            this.allHorsesIds = data

            this.renderHorses()
          },
          failure: null
        })
      },

      // 渲染逻辑
      renderHorses () {
        this.validHorses = []

        var ids = this.allHorsesIds.filter(_ => parseInt(_) !== 0)

        this.hasHorses = ids.length > 0

        // 获取马的详情
        ids.forEach(_ => {
          this.$root.callMatch({
            isProtected: false,
            params: _,
            methodName: API.GET_HORSE_WITH_AUCTION,
            methodType: 'GET',
            success: data => {
              // console.log(JSON.stringify(data))

              // [ genes, birthTime, cooldownEndBlock, damId, sireId, siringWithId, cooldownIndex, generation, isIco ]

              var gen = data[0] // 基因
              var speedValue = parseInt(gen.slice(0, 2))
              var accelerationValue = parseInt(gen.slice(2, 4))
              var strengthValue = parseInt(gen.slice(4, 6))
              var enduranceValue = parseInt(gen.slice(6, 8))
              var agileValue = parseInt(gen.slice(8, 10))
              var balancingValue = parseInt(gen.slice(10, 12))
              var bouncingValue = parseInt(gen.slice(12, 14))
              var reactionValue = parseInt(gen.slice(14, 16))

              var generationNum = data[7]

              var horse = {}

              horse.id = _
              horse.isSale = data[9]
              horse.name = HORSE_NAMES[horse.id]
              horse.imgUrl = require(`../../assets/img/horses/${_}.jpg`)
              horse.chartData = {
                rows: [
                  { 'Speed': 100,
                    'Acceleration': 100,
                    'Strength': 100,
                    'Endurance': 100,
                    'Agile': 100,
                    'Balancing': 100,
                    'Bouncing': 100,
                    'Reaction': 100
                  },
                  {
                    'Speed': speedValue,
                    'Acceleration': accelerationValue,
                    'Strength': strengthValue,
                    'Endurance': enduranceValue,
                    'Agile': agileValue,
                    'Balancing': balancingValue,
                    'Bouncing': bouncingValue,
                    'Reaction': reactionValue
                  }
                ]
              }

              var rateValue = (speedValue + accelerationValue + strengthValue + enduranceValue + agileValue + balancingValue + bouncingValue + reactionValue) / 160
              horse.rateValue = Math.ceil(rateValue)

              horse.generationNum = parseInt(generationNum)

              horse.eth = 0

              this.validHorses.push(horse)

              this.$root.callMatch({
                isProtected: false,
                // token_id
                params: _,
                methodName: API.GET_CURRENT_PRICE,
                methodType: 'GET',
                success: data => {
                  console.log('cancel = ' + JSON.stringify(data))

                  horse.eth = parseInt(data) / 1000000000000000000
                },
                failure: null
              })
            },
            failure: null
          })
        })
      }
    }
  }

  import { API, HORSE_NAMES } from '../../util/constants'
</script>

<style scoped>
#home {
  width: 100%;
  height: 420px;
  margin-top: 78px;
  margin-left: 12px;
}

.profile-info-cell {
  height: 120px;
  width: 100%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

/* 马区域的css */

.card-cell {
  height: 424px;
  max-width: 200;
}

.card-col {
  width: 24%;
  margin: 4px;
}

.card-bottom {
  margin-top: 8px;
}

.skill-charts {
  /* padding-top: 0; */
  /* margin-top: 0; */
  /* width: 100%; */
  /* margin-top: -20px; */
  /* height: 200px; */
  max-height: 290px;
  max-width: 380px;
  /* margin: 10px; */
}

.card-down {
  bottom: 0px;
}

.rate {
  margin-top: 10px;
}

</style>
